package com.liaowei.user.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.liaowei.common.BaseResponse;
import com.liaowei.common.ResultUtils;
import com.liaowei.model.domain.User;
import com.liaowei.model.param.ModifyPasswordParam;
import com.liaowei.model.param.SignupUserParam;
import com.liaowei.model.vo.UserVO;
import com.liaowei.user.model.param.PageUserParam;
import com.liaowei.user.model.param.UserParam;
import com.liaowei.user.service.UserService;
import com.liaowei.util.PasswordUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

@RestController
@RequiredArgsConstructor
@Validated
public class UserController {

    private final UserService userService;


    // 根据昵称分页查询用户列表
    @GetMapping("listByNickname")
    public BaseResponse<IPage<User>> listByNickname(@RequestParam int pageNum,
                                                    @RequestParam int pageSize,
                                                    String nickname) {
        return ResultUtils.success(userService.searchPageUserListByNickname(nickname,pageNum,pageSize));
    }

    // 修改密码
    @PutMapping("updatePassword")
    public BaseResponse<String> updatePassword(@RequestBody ModifyPasswordParam passwordParam) {
        return ResultUtils.success(userService.modifyPassword(passwordParam));
    }

    // 根据用户id查询用户信息
    @GetMapping("{userId}")
    public BaseResponse<UserVO> getById(@PathVariable
                                        @NotNull(message = "id不能为空")
                                        @Min(value = 1, message = "请输入合法id")
                                        Long userId) {
        return ResultUtils.success(userService.searchByUserId(userId));
    }

    // 修改用户信息
    @PutMapping
    public BaseResponse<String> update(@RequestBody @Validated UserParam userParam) {
        return ResultUtils.success(userService.modify(userParam));
    }

    // 后台管理-分页查询
    @PostMapping("manage/page")
    public BaseResponse<IPage<UserVO>> list(@RequestBody @Validated PageUserParam pageUserParam) {
        return ResultUtils.success(userService.pageList(pageUserParam));
    }

    // 用户退出
    @GetMapping("logout")
    public BaseResponse<String> logout() {
        return ResultUtils.success(userService.logout());
    }

    // 用户注册
    @PostMapping("signup")
    public BaseResponse<String> signup(@RequestBody @Validated SignupUserParam signupUserParam) {
        // 判断密码是否正确
        PasswordUtils.matchPassword(signupUserParam.getPassword(), signupUserParam.getCheckPassword());
        return ResultUtils.success(userService.signup(signupUserParam));
    }
}
